package com.eight.cloud.openapi.util;

import com.eight.cloud.openapi.annotations.OpenApi;
import com.eight.cloud.openapi.interfaces.InterfaceHandler;
import com.eight.cloud.openapi.model.vo.InterfaceVo;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.*;
import java.util.stream.Collectors;

import static com.eight.cloud.core.global.constant.StrConstant.COMMA;

/**
 * 接口工具
 *
 * @ClassName: InterfaceUtil
 * @Author: TXC
 * @Date: 2024-11-18 10:11
 **/
public class InterfaceUtil {
    private final ApplicationContext applicationContext;
    private final InterfaceHandler interfaceHandler;

    public InterfaceUtil(ApplicationContext applicationContext, InterfaceHandler interfaceHandler) {
        this.applicationContext = applicationContext;
        this.interfaceHandler = interfaceHandler;
    }

    /**
     * 获取系统所有开放接口
     */
    public void autoFindOpenApi() {
        // 获取controller相关bean
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        // 获取method
        Map<RequestMappingInfo, HandlerMethod> methodMap = mapping.getHandlerMethods();
        // 获取methodMap的key集合
        for (Map.Entry<RequestMappingInfo, HandlerMethod> info : methodMap.entrySet()) {
            if (info.getValue().hasMethodAnnotation(OpenApi.class)) {
                // controller url集合
                Set<String> urlSet = new HashSet<>();
                if (info.getKey().getPatternsCondition() != null) {
                    urlSet = info.getKey().getPatternsCondition().getPatterns();
                };
                Set<RequestMethod> urlMethod = info.getKey().getMethodsCondition().getMethods();
                Set<String> urlMethodStrSet = urlMethod.stream().map(RequestMethod::name).collect(Collectors.toSet());
                // controller url拼接路由前缀
                String url = String.join(COMMA, urlSet);
                String method = String.join(COMMA, urlMethodStrSet);
                InterfaceVo interfaceVo = new InterfaceVo();
                interfaceVo.setInterfaceUrl(url);
                interfaceVo.setInterfaceDetail(info.getValue().getMethodAnnotation(OpenApi.class));
                interfaceVo.setMethod(method);
                interfaceHandler.handle(interfaceVo);
            }
        }
    }
}
